#include "dlwindow.h"
#include <QProgressBar>
#include <string>
#include <unistd.h>
#include <stdio.h>

using namespace std;

DLWindow::DLWindow(QWidget *parent,string filename) : QDialog(parent)
{
    setWindowTitle(tr(filename.c_str()));
    l_filename = new QLabel(this);
    l_filename->setText(filename.c_str());
    l_filename->move(10,10);

    progress=new QProgressBar(this);
    progress->move(10,20);
    progress->setValue(0);
}

void DLWindow::launch(Connexion *conex, string fileName, string author,string dir)
{
    Connection connection = conex->request_connection(fileName, author);
    float progres;
    // Connection au client possédant le fichier souhaité
    MySocket socket;
    socket.myConnect(connection.ip, connection.port);
    // Demande du fichier souhaité
    char c_fileName[256];
    strcpy(c_fileName, fileName.c_str());
    socket.write(c_fileName, 256*sizeof(char));
    // Récupération de la taille du fichier souhaité
    uint32_t size;
    socket.read(&size, sizeof(uint32_t));
    ostringstream name;
    name <<dir<<"/"<< fileName;
    QFile file(name.str().c_str());
    file.open(QIODevice::WriteOnly);
    QDataStream out(&file);
    if(size == 0)
    {
        // ERROR fichier indisponible
    }
    else
    {
        uint32_t byteLoaded = 0;
        char buffer[BUFFER_SIZE+1];
        buffer[BUFFER_SIZE] = '\0';
        while (byteLoaded<size)
        {
            uint32_t byteRead = socket.read(buffer, BUFFER_SIZE);
            byteLoaded += byteRead;
            out.writeRawData(buffer, byteRead);
            progres=(byteLoaded/(float)size)*100;
            if(progres>=100)
                progress->setValue(100);
            else
                progress->setValue(progres);
        }
        file.close();
    }

}
